package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.cache.service.IStrategyRedisService;
import cn.wolfcode.luowowo.domain.Destination;
import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.domain.StrategyCatalog;
import cn.wolfcode.luowowo.query.SearchQueryObject;
import cn.wolfcode.luowowo.query.StrategyQuery;
import cn.wolfcode.luowowo.repository.StrategyRepository;
import cn.wolfcode.luowowo.service.IDestinationService;
import cn.wolfcode.luowowo.service.IStrategyCatalogService;
import cn.wolfcode.luowowo.service.IStrategyService;
import cn.wolfcode.luowowo.service.IStrategyThemeService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class StrategyServiceImpl implements IStrategyService {
    @Autowired
    private StrategyRepository strategyRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IStrategyCatalogService strategyCatalogService;

    @Autowired
    private IStrategyThemeService strategyThemeService;

    @Autowired
    private IStrategyRedisService strategyRedisService;

    @Autowired
    private IDestinationService destinationService;

    @Override
    public void insert(Strategy strategy) {
        strategy.setId(null);
        StrategyCatalog catalog = strategyCatalogService.select(strategy.getCatalogId());
        strategy.setCatalogName(catalog.getName());
        strategy.setDestId(catalog.getDestId());
        strategy.setDestName(catalog.getDestName());
        strategy.setCreateTime(new Date());
        strategy.setThemeName(strategyThemeService.select(strategy.getThemeId()).getName());
        List<Destination> toasts = destinationService.findByParentId(catalog.getDestId());
        if (toasts != null && toasts.size() > 0) {
            strategy.setIsabroad("中国".equals(toasts.get(0).getName())?Strategy.ABROAD_NO:Strategy.ABROAD_YES);
        }
        strategyRepository.save(strategy);
    }

    @Override
    public void update(Strategy strategy) {
        Strategy strategy1 = strategyRepository.findById(strategy.getId()).get();//解决创建时间没传的问题
        StrategyCatalog catalog = strategyCatalogService.select(strategy.getCatalogId());
        strategy1.setCatalogId(strategy.getCatalogId());
        strategy1.setCatalogName(catalog.getName());
        strategy1.setDestId(catalog.getDestId());
        strategy1.setDestName(catalog.getDestName());
        strategy1.setThemeName(strategyThemeService.select(strategy.getThemeId()).getName());
        List<Destination> toasts = destinationService.findByParentId(catalog.getDestId());
        if (toasts != null && toasts.size() > 0) {
            strategy1.setIsabroad("中国".equals(toasts.get(0).getName())?Strategy.ABROAD_NO:Strategy.ABROAD_YES);
        }
        strategy1.setViewnum(strategy.getViewnum());
        strategy1.setReplynum(strategy.getReplynum());
        strategy1.setFavornum(strategy.getFavornum());
        strategy1.setSharenum(strategy.getSharenum());
        strategy1.setThumbsupnum(strategy.getThumbsupnum());
        strategyRepository.save(strategy1);
    }

    @Override
    public void delete(String id) {
        strategyRepository.deleteById(id);
    }

    @Override
    public Strategy select(String id) {
        return strategyRepository.findById(id).get();
    }

    @Override
    public void changeState(int state, String id) {
        Strategy strategy = strategyRepository.findById(id).get();
        strategy.setState(state);
        strategyRepository.save(strategy);
    }

    @Override
    public List<Strategy> getViewnumTop3(String destId) {
        List<Strategy> strategies = strategyRepository.findByDestIdOrderByViewnumDesc(destId);
        if (strategies.size() >= 3) {
            strategies = strategies.subList(0, 3);
        }
        return strategies;
    }

    @Override
    public List<Strategy> listAll() {
        return strategyRepository.findAll();
    }

    @Override
    public boolean thumbup(String token, String sid) {
        boolean ret = strategyRedisService.thumbup(token, sid);
        if (ret) {
            Strategy strategy = this.select(sid);
            int thumbsupnum = strategy.getThumbsupnum();
            strategy.setThumbsupnum(thumbsupnum + 1);
            strategyRepository.save(strategy);
        }
        return ret;
    }

    @Override
    public void favor(String sid) {
        Strategy strategy = strategyRepository.findById(sid).get();
        strategy.setFavornum(strategy.getFavornum() + 1);
        strategyRepository.save(strategy);
    }

    @Override
    public void favorNot(String sid) {
        Strategy strategy = strategyRepository.findById(sid).get();
        strategy.setFavornum(strategy.getFavornum() - 1);
        strategyRepository.save(strategy);
    }

    @Override
    public Page<Strategy> query(StrategyQuery qo) {
        Query query = new Query();
        if (StringUtils.hasLength(qo.getDestId())) {
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        if (StringUtils.hasLength(qo.getThemeId())) {
            query.addCriteria(Criteria.where("themeId").is(qo.getThemeId()));
        }
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, 5, Sort.Direction.ASC, "_id");

        return DBHelper.query(mongoTemplate, Strategy.class, query, pageable);
    }

    @Override
    public List<Strategy> listByKeyword(SearchQueryObject qo) {
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.orOperator(
                Criteria.where("title").regex(".*" + qo.getKeyword() + ".*"),
                Criteria.where("subTitle").regex(".*" + qo.getKeyword() + ".*"),
                Criteria.where("summary").regex(".*" + qo.getKeyword() + ".*")
        );
        query.addCriteria(criteria);
        List<Strategy> strategies = mongoTemplate.find(query, Strategy.class, "strategy");
        return strategies;
    }

    @Override
    public Page<Strategy> queryByKeyword(SearchQueryObject qo) {
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.andOperator(
                Criteria.where("title").regex(".*" + qo.getKeyword() + ".*"),
                Criteria.where("subTitle").regex(".*" + qo.getKeyword() + ".*"),
                Criteria.where("summary").regex(".*" + qo.getKeyword() + ".*")
        );
        query.addCriteria(criteria);
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, 5, Sort.Direction.ASC, "_id");
        return DBHelper.query(mongoTemplate, Strategy.class, query, pageable);
    }

    @Override
    public void updateVO(Strategy s) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(s.getId()));
        DBHelper.update(mongoTemplate, query, s, "viewnum", "replynum"
                , "favornum", "sharenum", "thumbsupnum");
    }
}
